<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品类型" prop="productType">
      <el-radio-group v-model="formData.productType" @change="handleProductTypeChange">
        <el-radio :value="3">门店商品</el-radio>
        <el-radio :value="2">农场商品</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData.productType === 3" label="所属门店" prop="storeId">
      <el-input
        v-model="selectedStoreName"
        placeholder="请选择门店"
        clearable
        readonly
        @clear="handleClearStore"
      >
        <template #suffix>
          <Icon
            icon="ep:search"
            class="cursor-pointer hover:text-primary"
            @click="openStoreDialog"
          />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item v-if="formData.productType === 2" label="所属农场" prop="farmId">
      <el-input
        v-model="selectedFarmName"
        placeholder="请选择农场"
        clearable
        readonly
        @clear="handleClearFarm"
      >
        <template #suffix>
          <Icon
            icon="ep:search"
            class="cursor-pointer hover:text-primary"
            @click="openFarmDialog"
          />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
      />
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="商品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品标签" prop="label">
      <el-select
        v-if="!isDetail"
        v-model="selectedLabels"
        class="w-80"
        clearable
        multiple
        placeholder="请选择商品标签"
        @change="handleLabelChange"
      >
        <el-option
          v-for="item in labelOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <span v-else>
        <el-tag v-for="label in displayLabels" :key="label" class="mr-2" type="info">
          {{ label }}
        </el-tag>
        <span v-if="displayLabels.length === 0">无</span>
      </span>
    </el-form-item>
    <el-form-item label="推荐商品" prop="isRecommend">
      <el-switch
        v-if="!isDetail"
        v-model="formData.isRecommend"
        :active-value="1"
        :inactive-value="0"
        active-text="是"
        inactive-text="否"
      />
      <span v-else>{{ formData.isRecommend === 1 ? '是' : '否' }}</span>
    </el-form-item>
    <el-form-item label="库存预警" prop="alertStock">
      <el-input-number
        v-if="!isDetail"
        v-model="formData.alertStock"
        :min="0"
        :precision="0"
        class="w-80!"
        placeholder="请输入库存预警值"
      />
      <span v-else>{{ formData.alertStock }}</span>
    </el-form-item>
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />
    </el-form-item>
  </el-form>

  <!-- 门店选择弹窗 -->
  <StoreSelectDialog ref="storeDialogRef" @confirm="handleStoreConfirm" />
  <!-- 农场选择弹窗 -->
  <FarmSelectDialog ref="farmDialogRef" @confirm="handleFarmConfirm" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'
import StoreSelectDialog from './StoreSelectDialog.vue'
import FarmSelectDialog from './FarmSelectDialog.vue'
import { StoreInfoVO } from '@/api/direct/storeinfo'
import { InfoVO } from '@/api/farm/info'

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗

// 扩展 Spu 类型，添加新字段
interface ExtendedSpu extends Spu {
  label?: string // 商品标签
  isRecommend?: number // 是否推荐商品：0-否，1-是
  alertStock?: number // 库存预警
  productType?: number // 商品类型：2-农场商品，3-门店商品
  storeId?: number // 门店ID
  storeName?: string // 门店名称
  farmId?: number // 农场ID
  farmName?: string // 农场名称
}

const formRef = ref() // 表单 Ref
const formData = reactive<ExtendedSpu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  label: '', // 商品标签
  isRecommend: 0, // 是否推荐商品：0-否，1-是
  alertStock: 0, // 库存预警
  productType: 2, // 商品类型：2-农场商品，3-门店商品，默认农场商品
  storeId: undefined, // 门店ID
  farmId: undefined // 农场ID
})

// 选择器显示名称
const selectedStoreName = ref('') // 选中的门店名称
const selectedFarmName = ref('') // 选中的农场名称

// 标签相关
const selectedLabels = ref<string[]>([]) // 选中的标签数组
const labelOptions = ref<string[]>([
  '新品',
  '热销',
  '推荐',
  '限时特惠',
  '精品',
  '有机',
  '绿色',
  '无公害',
  '当季',
  '特价'
]) // 预设标签选项

// 用于详情页展示的标签数组
const displayLabels = computed(() => {
  if (!formData.label) return []
  return formData.label.split(',').filter((item) => item.trim())
})

// 处理标签选择变化
const handleLabelChange = (value: string[]) => {
  formData.label = value.join(',')
}
const rules = reactive({
  name: [required],
  productType: [required],
  storeId: [
    {
      required: true,
      validator: (_rule: any, value: any, callback: any) => {
        if (formData.productType === 3 && !value) {
          callback(new Error('请选择门店'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  farmId: [
    {
      required: true,
      validator: (_rule: any, value: any, callback: any) => {
        if (formData.productType === 2 && !value) {
          callback(new Error('请选择农场'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  categoryId: [required],
  keyword: [required],
  introduction: [required],
  picUrl: [required],
  sliderPicUrls: [required]
})

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    // 处理标签回显：将字符串转换为数组
    const extendedData = data as any
    if (extendedData.label) {
      selectedLabels.value = extendedData.label.split(',').filter((item: string) => item.trim())
    } else {
      selectedLabels.value = []
    }
    
    // 处理门店/农场名称回显
    if (extendedData.storeName) {
      selectedStoreName.value = extendedData.storeName
    }
    if (extendedData.farmName) {
      selectedFarmName.value = extendedData.farmName
    }
  },
  {
    immediate: true
  }
)

/** 监听 formData.label 变化，同步到 selectedLabels */
watch(
  () => formData.label,
  (newLabel) => {
    if (newLabel) {
      const labels = newLabel.split(',').filter((item) => item.trim())
      // 只有当值不同时才更新，避免循环
      if (labels.join(',') !== selectedLabels.value.join(',')) {
        selectedLabels.value = labels
      }
    } else {
      selectedLabels.value = []
    }
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 初始化 */
const categoryList = ref<CategoryVO[]>([]) // 商品分类树

/** 商品类型改变 */
const handleProductTypeChange = () => {
  // 清空之前选择的门店或农场
  formData.storeId = undefined
  formData.farmId = undefined
  selectedStoreName.value = ''
  selectedFarmName.value = ''
}

/** 门店选择弹窗 */
const storeDialogRef = ref()
const openStoreDialog = () => {
  storeDialogRef.value?.open()
}

/** 门店选择确认 */
const handleStoreConfirm = (store: StoreInfoVO) => {
  formData.storeId = store.id
  formData.storeName = store.storeName
  selectedStoreName.value = store.storeName
}

/** 清空门店选择 */
const handleClearStore = () => {
  formData.storeId = undefined
  formData.storeName = ''
  selectedStoreName.value = ''
}

/** 农场选择弹窗 */
const farmDialogRef = ref()
const openFarmDialog = () => {
  farmDialogRef.value?.open()
}

/** 农场选择确认 */
const handleFarmConfirm = (farm: InfoVO) => {
  formData.farmId = farm.id
  formData.farmName = farm.farmName
  selectedFarmName.value = farm.farmName
}

/** 清空农场选择 */
const handleClearFarm = () => {
  formData.farmId = undefined
  formData.farmName = ''
  selectedFarmName.value = ''
}

onMounted(async () => {
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({ type: 2 })
  categoryList.value = handleTree(data, 'id')
})
</script>
